<?php
/**
 * Twig 模板 拓展
 * User: 孙家浩
 * Date: 2019/4/4
 * Time: 11:24
 */

namespace Twig;

use Twig\Extension\AbstractExtension;


class TwigExpand extends AbstractExtension
{
	/**
	 * 过滤器 拓展.
	 */
	public function getFilters()
	{
		return [];
	}

	/**
	 * 函数 拓展.
	 */
	public function getFunctions()
	{
		return [
			new TwigFunction('isController', array($this, 'isController')),
			new TwigFunction('action', array($this, 'isAction')),
			new TwigFunction('image', array($this, 'getImage')),
			new TwigFunction('avatar', array($this, 'getAvatar')),
			new TwigFunction('load', array($this, 'getLoad'), ['is_safe' => ['html']]),
			new TwigFunction('info', array($this, 'getInfo'), ['is_safe' => ['html']]),
		];
	}

	/**
	 * Token的解析器 拓展.
	 */
	public function getTokenParsers()
	{
		return [];
	}

	/**
	 * 节点访问器 拓展.
	 */
	public function getNodeVisitors()
	{
		return [];
	}

	/**
	 * 测试 拓展.
	 */
	public function getTests()
	{
		return [];
	}

	/**
	 * 运算符 拓展.
	 * @return array<array> First array of unary operators, second array of binary operators
	 */
	public function getOperators()
	{
		return [];
	}

	public function isController($method, $action = 'active')
	{
		$method = explode(',', $method);
		if (in_array(request()->controller(), $method)) {
			return $action;
		}
		return '';
	}

	public function isAction($method, $action = 'active')
	{
		$method = explode(',', strtolower($method));
		if (in_array(strtolower(request()->action()), $method)) {
			return $action;
		}
		return '';
	}

	public function getImage($path, $default = 'images/default.png')
	{
		$path = $this->isPath($path,$default);
		return $path;
	}

	public function getAvatar($path, $default = 'images/avatar.png')
	{
		$path = $this->isPath($path,$default);
		return $path;
	}

	public function isPath($path,$default)
	{
		if (!empty($path)) {
			if (preg_match('/^http:\/\//', $path)) {
				//远程文件
				if (ini_get('allow_url_fopen')) {
					if (@fopen($path, 'r')) return $path;
				} else {
					$url = parse_url($path);
					$host = $url['host'];
					$path = $url['path'];
					$fp = fsockopen($host, 80, $errno, $errstr, 10);
					if ($fp) {
						fputs($fp, "GET {$path} HTTP/1.1 \r\nhost:{$host}\r\n\r\n");
						if (preg_match('/HTTP\/1.1 200/', fgets($fp, 1024))) return $path;
					}
				}
			} else {
				if (!in_array('..', explode('/', $path))) {
					$path = 'static/' . $path;
				} else {
					$path = substr($path, 3);
				}

				if (file_exists($path)) {
					return '/'.$path;
				}
			}
		}
		return '/static/' . $default;
	}

	public function getLoad(...$loads)
	{
		$css = $js = '';
		foreach ($loads as &$load) {
			$category = explode('.', $load);
			$load = '/static/' . $load;
			if (end($category) === 'css') {
				$css .= "<link rel='stylesheet' type='text/css' href='{$load}'/>\n\r";
			} elseif (end($category) === 'js') {
				$js .= "<script type='text/javascript' src='{$load}'></script>\n\r";
			}
		}

		return $css . $js;
	}

}
